package com.jvxb.demo.service.impl;

import com.jvxb.demo.config.RabbitMqConfig;
import com.jvxb.demo.service.RabbitmqService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author jvxb
 * @since 2023-02-04
 */
@Service
public class RabbitmqServiceImpl implements RabbitmqService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void send(String exchange, String routingKey, String message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    @RabbitListener(queues = {RabbitMqConfig.SMS_QUEUE, RabbitMqConfig.MAIL_QUEUE})
    public void handleSmsMsg(String msg, Message message) {
        String consumerQueue = message.getMessageProperties().getConsumerQueue();
        try {
            System.out.println(String.format("队列%s接收到消息：%s", consumerQueue, msg));
        } catch (Exception e) {
            //可以通过另外途径（mysql/redis）记录这条消息，或者投递到死信队列。
            System.out.println(String.format("队列%s处理消息%s异常：%s，", consumerQueue, msg, e.getMessage()));
        }
    }

}
